package com.wang.wangapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wang.wangapiclientsdk.model.User;

import java.util.HashMap;
import java.util.Map;

import static com.wang.wangapiclientsdk.utils.SignUtil.genSign;


/**
 * @author yandong
 */
public class WangApiClient {
    private String accessKey;
    private String secretKey;

    public WangApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    /**
     * 向服务端/name/getName接口发送请求
     */
    public String getNameByGet(String name) {

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result= HttpUtil.get("http://localhost:8080/name/getName", paramMap);
        System.out.println(result);

        return result;
    }

    /**
     * 向服务端name/postUrl接口发送请求
     */
    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result= HttpUtil.post("http://localhost:8080/name/postUrl", paramMap);
        System.out.println(result);

        return result;
    }


    /**
     * 向服务端name/postJson接口发送请求 (并携带API签名认证)
     * @param user 用户参数
     * @return 响应结果
     */
    public String getUsernameByPost(User user) {
        String userJsonStr = JSONUtil.toJsonStr(user);
        HttpResponse response = HttpRequest.post("http://localhost:8080/name/postJson")
                .addHeaders(getHeaderMap(userJsonStr))
                .body(userJsonStr)
                .execute();
        System.out.println(response.getStatus());
        String result = response.body();
        System.out.println(result);

        return result;
    }

    /**
     * 构造请求头
     * @param body 用户参数
     * @return 请求头
     */
    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("accessKey", accessKey); // ak (注意: sk一定不能发送给后端)
        headerMap.put("body", body); // 用户参数
        headerMap.put("nonce", RandomUtil.randomNumbers(4)); // 随机数
        headerMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000)); //时间戳
        headerMap.put("sign", genSign(body, secretKey)); // 签名

        return headerMap;
    }
}
